<?php

namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use App\Models\Member\CertificationCompany;
use App\Models\Member\CertificationEmail;
use App\Models\Member\CertificationPersonal;
use App\Models\Member\Member;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use App\Traits\Upload;
use Storage;

class AccountController extends Controller {
	use Upload;

	public function info( Request $request ) {
		return view( 'member.account.info' );
	}

	public function safe( Request $request ) {
		return view( 'member.account.safe' );
	}

	public function certification( Request $request ) {
		return view( 'member.account.certification' );
	}

	public function authEmail( Request $request ) {
		$user       = \auth( 'admin' )->user();
		$queryValue = $request->get( 'queryValue' );
		$limit =$request->get('limit',10);
		$data       = CertificationEmail::where( 'user_id', $user->id )->where( 'email', 'like',
			'%' . $queryValue . '%' )->orderBy(  'created_at','desc'  )->paginate( $limit );

		return view( 'member.account.auth-email', compact( 'data', 'queryValue' ) );
	}

	public function authEmailAdd( Request $request ) {
		if ( $request->isMethod( 'post' ) ) {
			$validator = Validator::make(
				$request->all(),
				[
					'email' => 'required|email',
				], [
					'email.required' => '邮箱必填',
					'email.email'    => '不是有效的邮箱地址',
				]
			);

			if ( $validator->fails() ) {
				$error      = collect( $validator->errors()->all() );
				$returnData = array(
					'code'  => '0',
					'msg'   => '验证失败',
					'data'  => $validator->errors()->first(),
					'error' => $error->toJson(),

				);

				return response()->json( $returnData, 500 );
			}
			$user         = \auth( 'admin' )->user();
			$token        = Str::random( 32 );
			$send_email   = $request->get( 'email' );
			$email_verify = CertificationEmail::where( 'email', $send_email )->where( 'user_id', $user->id )->first();

			if ( is_null( $email_verify ) ) {
				CertificationEmail::create( [
					'user_id'  => $user->id,
					'email'    => $send_email,
					'token'    => $token,
					'end_time' => date( 'Y-m-d H:i:s', time() + 3600 )
				] );
			} else {
				// echo '更新';
				if ( $email_verify->status > 0 ) {
					return $this->result_api( 400, 'error', [ 'error' => '已验证邮箱!' ] );
				}
				$email_verify->update( [
					'token'    => $token,
					'end_time' => date( 'Y-m-d H:i:s', time() + 3600 )
				] );
			}
			//模板发送
			Mail::send( 'public.email.certification_email', [
				'username' => '尊敬的会员',
				'site_name'     => config('base.email.MAIL_FROM_NAME',config('app.name')),
				'link'     => url( 'account/auth/email/check' ) . '?token=' . $token . '&email=' . $send_email
			],
				function ( $message ) use ( $send_email ) {
					$to = $send_email;
					$message->to( $to )->subject( '邮箱认证' );

					//在邮件中上传附件
//					$attachment = public_path('/storage/upload/invoice/FbF1d5V9QIWcNV7cObl1U9MAXNDwHXp7pA1Y2ZAq.png');
//					$message->attach($attachment,['as'=>'invoice.jpg']);
//					$message->attach($attachment,['as'=>now().'invoice.jpg']);
//					$message->attach($attachment);
				} );

			if ( count( Mail::failures() ) < 1 ) {
				return $this->result_api( 200, 'success' );
			} else {
				return $this->result_api( 400, 'error', [ 'error' => '发送邮件失败，请重试！' ] );
			}
		}

		return view( 'member.account.auth-email-add' );
	}

	public function authEmailCheck( Request $request ) {

		$validator = Validator::make(
			$request->all(),
			[
				'email' => 'required|email',
				'token' => 'required|min:32',
			], [
				'email.required' => '连接不合法',
				'email.email'    => '连接不合法',
				'token.required' => '连接不合法',
				'token.min'      => '连接不合法',
			]
		);

		if ( $validator->fails() ) {
			$error      = collect( $validator->errors()->all() );
			$returnData = array(
				'code'  => '0',
				'msg'   => '验证失败',
				'data'  => $validator->errors()->first(),
				'error' => $error->toJson(),

			);

			return view( 'public.jump.success' )->with( [
				'message'  => $returnData['data'],
				'url'      => '/',
				'jumpTime' => 3,
			] );
		}


		$res = CertificationEmail::where( 'token', $request->get( 'token' ) )->
		where( 'email', $request->get( 'email' ) )->
		where( 'end_time', '>', date( 'Y-m-d H:i:s' ) )->
		where( 'status', 0 )->first();
		if ( $res ) {
			$res->update( [ 'status' => 1 ] );

			return view( 'public.jump.success' )->with( [
				'message'  => '验证成功!',
				'url'      => '/account/auth/email',
				'jumpTime' => 3,
			] );
		} else {
			return view( 'public.jump.success' )->with( [
				'message'  => '验证已过期!',
				'url'      => '/account/auth/email',
				'jumpTime' => 3,
			] );
		}
	}

	public function authPersonal( Request $request ) {
		$user       = \auth( 'admin' )->user();
		$queryValue = $request->get( 'queryValue' );
		$queryType  = $request->get( 'queryType' );
		$limit      = $request->get( 'limit', 10 );
		$data       = [];
		if ( $queryType == 'name' ) {
			$data = CertificationPersonal::where( 'user_id', $user->id )->where( 'name', 'like',
				'%' . $queryValue . '%' )->orderBy(  'created_at','desc'  )->paginate( $limit );
		} elseif ( $queryType == 'number' ) {
			$data = CertificationPersonal::where( 'user_id', $user->id )->where( 'number', 'like',
				'%' . $queryValue . '%' )->orderBy( 'created_at','desc'  )->paginate( $limit );
		} else {
			$data = CertificationPersonal::where( 'user_id', $user->id )->orderBy( 'created_at','desc' )->paginate( $limit );
		}

		return view( 'member.account.auth-personal', compact( 'data', 'queryValue', 'queryType' ) );
	}

	public function authPersonalAdd( Request $request ) {
		if ( $request->isMethod( 'post' ) ) {
			$validator = Validator::make(
				$request->all(),
				[
					'name'   => 'required',
					'type'   => 'required',
					'number' => 'required',
					'image1' => 'required',
				], [
					'name.required'   => '姓名 必填',
					'type.required'   => '类型 必填',
					'number.required' => '号码 必填',
					'image1.required' => '图片 必填',
				]
			);

			if ( $validator->fails() ) {
				$error      = collect( $validator->errors()->all() );
				$returnData = array(
					'code'  => '0',
					'msg'   => '验证失败',
					'data'  => $validator->errors()->first(),
					'error' => $error->toJson(),

				);

				return response()->json( $returnData, 500 );
			}

			$user             = \auth( 'admin' )->user();
			$data             = $request->except( '_token' );
			$data ['user_id'] = $user->id;
			$data ['status']  = 0;

			$res = CertificationPersonal::create( $data );
			if ( $res ) {
				return $this->result_api( 200, 'success' );
			} else {
				return $this->result_api( 400, 'error', [ 'error' => '提交失败!' ] );
			}

		}

		return view( 'member.account.auth-personal-add' );
	}

	public function authPersonalDel( Request $request ) {
		if ( $request->isMethod( 'post' ) ) {
			$validator = Validator::make(
				$request->all(),
				[
					'id' => 'required',
				], [
					'id.required' => 'id错误',
				]
			);

			if ( $validator->fails() ) {
				$error      = collect( $validator->errors()->all() );
				$returnData = array(
					'code'  => '0',
					'msg'   => '验证失败',
					'data'  => $validator->errors()->first(),
					'error' => $error->toJson(),

				);

				return response()->json( $returnData, 500 );
			}

			$user    = \auth( 'admin' )->user();
			$auth_id = $request->get( 'id' );
			$res     = CertificationPersonal::where( 'user_id', $user->id )->where( 'id', $auth_id )->delete();
			if ( $res ) {
				return $this->result_api( 200, 'success' );
			} else {
				return $this->result_api( 400, 'error', [ 'error' => '提交失败!' ] );
			}
		}
	}

	public function authCompany( Request $request ) {
		$user       = \auth( 'admin' )->user();
		$queryValue = $request->get( 'queryValue' );
		$queryType  = $request->get( 'queryType' );
		$limit = $request->get( 'limit' ,10);
		$data       = [];
		if ( $queryType == 'name' ) {
			$data = CertificationCompany::where( 'user_id', $user->id )->where( 'name', 'like',
				'%' . $queryValue . '%' )->orderBy(  'created_at','desc'  )->paginate( $limit );
		} elseif ( $queryType == 'number' ) {
			$data = CertificationCompany::where( 'user_id', $user->id )->where( 'number', 'like',
				'%' . $queryValue . '%' )->orderBy(  'created_at','desc'  )->paginate( $limit );
		} else {
			$data = CertificationCompany::where( 'user_id', $user->id )->orderBy(  'created_at','desc'  )->paginate( $limit );
		}

		return view( 'member.account.auth-company', compact( 'data', 'queryValue', 'queryType' ) );
	}

	public function authCompanyAdd( Request $request ) {
		if ( $request->isMethod( 'post' ) ) {
			$validator = Validator::make(
				$request->all(),
				[
					'name'   => 'required',
					'type'   => 'required',
					'number' => 'required',
					'image1' => 'required',
				], [
					'name.required'   => '姓名 必填',
					'type.required'   => '类型 必填',
					'number.required' => '号码 必填',
					'image1.required' => '图片 必填',
				]
			);

			if ( $validator->fails() ) {
				$error      = collect( $validator->errors()->all() );
				$returnData = array(
					'code'  => '0',
					'msg'   => '验证失败',
					'data'  => $validator->errors()->first(),
					'error' => $error->toJson(),

				);

				return response()->json( $returnData, 500 );
			}

			$user             = \auth( 'admin' )->user();
			$data             = $request->except( '_token' );
			$data ['user_id'] = $user->id;
			$data ['status']  = 0;

			$res = Order::create( $data );
			if ( $res ) {
				return $this->result_api( 200, 'success' );
			} else {
				return $this->result_api( 400, 'error', [ 'error' => '提交失败!' ] );
			}

		}

		return view( 'member.account.auth-company-add' );
	}

	public function authCompanyDel( Request $request ) {
		if ( $request->isMethod( 'post' ) ) {
			$validator = Validator::make(
				$request->all(),
				[
					'id' => 'required',
				], [
					'id.required' => 'id错误',
				]
			);

			if ( $validator->fails() ) {
				$error      = collect( $validator->errors()->all() );
				$returnData = array(
					'code'  => '0',
					'msg'   => '验证失败',
					'data'  => $validator->errors()->first(),
					'error' => $error->toJson(),

				);

				return response()->json( $returnData, 500 );
			}

			$user    = \auth( 'admin' )->user();
			$auth_id = $request->get( 'id' );
			$res     = Order::where( 'user_id', $user->id )->where( 'id', $auth_id )->delete();
			if ( $res ) {
				return $this->result_api( 200, 'success' );
			} else {
				return $this->result_api( 400, 'error', [ 'error' => '提交失败!' ] );
			}
		}
	}

	public function editPW( Request $request ) {
		if ( $request->isMethod( 'post' ) ) {
			$validator = Validator::make(
				$request->all(),
				[
					'password'           => 'required|min:6',
					'newPassword'        => 'required|min:6',
					'confirmNewPassword' => 'same:newPassword',
				], [
					'password.required'       => '密码必填',
					'password.min'            => '密码过短',
					'password2.same'          => '两次密码 不一致',
					'confirmNewPassword.same' => '两次密码 不一致',
					'newPassword.required'    => '新密码 必填',
					'newPassword.min'         => '新密码 过短',
				]
			);

			if ( $validator->fails() ) {
				$error      = collect( $validator->errors()->all() );
				$returnData = array(
					'code'  => '0',
					'msg'   => '验证失败',
					'data'  => $validator->errors()->first(),
					'error' => $error->toJson(),

				);

				return response()->json( $returnData, 500 );
			}
			$user = \auth( 'admin' )->user();
			$hash = Hash::check( $request->get( 'password' ), $user->password );
			if ( $hash ) {
				$res = Member::where( 'id',
					$user->id )->update( [ 'password' => bcrypt( $request->get( 'newPassword' ) ) ] );
				if ( $res ) {
					return $this->result_api( 200, 'success' );
				} else {
					return $this->result_api( 400, 'error', [ 'error' => '修改失败!' ] );
				}
			} else {
				return $this->result_api( 400, 'error', [ 'error' => '原密码错误!' ] );
			}
		}

		return view( 'member.account.edit-pw' );
	}

}
